package com.agilestudio.ifinance.web.account;

import java.util.Iterator;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.agilestudio.ifinance.entity.account.Contact;
import com.agilestudio.ifinance.service.account.ContactService;
import com.agilestudio.ifinance.web.AbstractController;

@Controller
@RequestMapping(value = "contact")
public class ContactController extends AbstractController{

	@Autowired
	private ContactService contactService;

	@RequestMapping("/index")
	public String listContacts(Map<String, Object> map) {

		map.put("contact", new Contact());
		map.put("contactList", contactService.listContact());

		return "contact";
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String addContact(@Valid @ModelAttribute("contact")
	Contact contact, BindingResult result) {
		for (Iterator<ObjectError> iterator = result.getAllErrors().iterator(); iterator.hasNext();) {
			ObjectError type = (ObjectError) iterator.next();
			log.info("save error= " + type.getObjectName() +";" + type.getCode()+";" + type.getDefaultMessage() + ";");
			
		}
		if (!result.hasErrors()){
			contactService.addContact(contact);
		}

		return "contact";
	}

	@RequestMapping("/delete/{contactId}")
	public String deleteContact(@PathVariable("contactId")
	Long contactId) {

		contactService.removeContact(contactId);

		return "redirect:/index";
	}
}
